SET NUMERIC_ROUNDABORT OFF
GO
SET ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT, QUOTED_IDENTIFIER, ANSI_NULLS ON
GO
IF EXISTS (SELECT * FROM tempdb..sysobjects WHERE id=OBJECT_ID('tempdb..#tmpErrors')) DROP TABLE #tmpErrors
GO
CREATE TABLE #tmpErrors (Error int)
GO
SET XACT_ABORT ON
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
GO
BEGIN TRANSACTION
GO

/*===================================BEGIN=================================*/

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


ALTER TABLE dbo.CONTACTS_IMPORT_HISTORY
	DROP CONSTRAINT FK_CONTACTS_IMPORT_HISTORY_IMPORTS
GO
ALTER TABLE dbo.IMPORTS SET (LOCK_ESCALATION = TABLE)
GO
ALTER TABLE dbo.CONTACTS_IMPORT_HISTORY
	DROP CONSTRAINT FK_CONTACTS_IMPORT_HISTORY_CONTACTS
GO
ALTER TABLE dbo.CONTACTS SET (LOCK_ESCALATION = TABLE)
GO
ALTER TABLE dbo.CONTACTS_IMPORT_HISTORY ADD CONSTRAINT
	FK_CONTACTS_IMPORT_HISTORY_CONTACTS FOREIGN KEY
	(
	TARGET_ID
	) REFERENCES dbo.CONTACTS
	(
	ID
	) ON UPDATE  NO ACTION 
	 ON DELETE  CASCADE 
	
GO
ALTER TABLE dbo.CONTACTS_IMPORT_HISTORY ADD CONSTRAINT
	FK_CONTACTS_IMPORT_HISTORY_IMPORTS FOREIGN KEY
	(
	IMPORT_ID
	) REFERENCES dbo.IMPORTS
	(
	IMPORT_ID
	) ON UPDATE  NO ACTION 
	 ON DELETE  CASCADE 
	
GO
ALTER TABLE dbo.CONTACTS_IMPORT_HISTORY SET (LOCK_ESCALATION = TABLE)
GO


/*===================================END=================================*/


IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO

IF EXISTS (SELECT * FROM #tmpErrors) ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT>0 BEGIN
PRINT 'The database update succeeded'

-- Record the script update
INSERT INTO dbo.[SchemaChanges]
       ([MajorReleaseNumber]
       ,[MinorReleaseNumber]
       ,[BuildReleaseNumber]
       ,[RevisionReleaseNumber]
       ,[ScriptName]
       ,[DateApplied]
       ,[Description])
VALUES
       ('1'
       ,'00'
       ,'01'
       ,'005'
       ,'Upgrade-1.00.01.005.sql'	   
       ,GETDATE()
	   ,'Cascade delete for contact import history')
	   COMMIT TRANSACTION
END
ELSE PRINT 'The database update failed'
GO
DROP TABLE #tmpErrors
GO        

